package com.base.schema.singleton;

/**
 * 懒汉式5 静态内部类（线程安全）这个方法比较常用
 * @ClassName: SingletonDemo7
 * @Description: 
 * @Author xuyou
 * @DateTime 2021年3月2日 上午10:59:43
 */
public class SingletonDemo7 {
  
	//1: 构造方法私有化,外部无法使用new构造方法创建对象
	private SingletonDemo7() {};
	
	 /*2.编写一个静态内部类*/
    private static class SingletonInstence {
        private static final SingletonDemo7 INSTENCE = new SingletonDemo7();
    }
	
	//3: 提供一个对外获取实例的方法
	public static SingletonDemo7 getInstence() {
		return SingletonInstence.INSTENCE;
	}
	
	public static void main(String[] args) {
		//单线程获取无影响
//		SingletonDemo3 instence1 = SingletonDemo3.getInstence();
//		SingletonDemo3 instence2 = SingletonDemo3.getInstence();
//		System.out.println(instence1 == instence2);
		
		//模拟线程不安全
		for (int i = 0; i < 10; i++) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					SingletonDemo7 instence1 = SingletonDemo7.getInstence();	
					System.out.println(instence1);
				}
			}).start();
		}
		
	}
	
}
